<template>
  <div class="list-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>{{ pageConfig.title }}</h2>
      <div class="tabs-container">
        <el-tabs v-model="activeTab" @tab-change="handleTabChange">
          <el-tab-pane 
            v-for="tab in pageConfig.tabs" 
            :key="tab.key"
            :label="tab.label" 
            :name="tab.key"
          />
        </el-tabs>
      </div>
    </div>
    
    <!-- 1. 按钮部分 -->
    <ActionButtons 
      :has-selection="selectedRows.length > 0"
      :buttons="actionButtons"
      @add="handleAdd"
      @edit="handleEdit"
      @view="handleView"
      @delete="handleBatchDelete"
      @refresh="handleRefresh"
      @export="handleExport"
      @all="() => ElMessage.info('全部客户')"
      @unpaid="() => ElMessage.info('未清客户')"
      @reset="handleReset"
    />
    
    <!-- 2. 搜索栏部分 -->
    <SearchForm 
      v-model="searchParams"
      @search="handleSearch"
      @reset="handleReset"
    />
    
    <!-- 3. 列表部分 -->
    <DataTable 
      :table-data="tableData"
      :total="total"
      :current-page="pagination.page"
      :page-size="pagination.size"
      @selection-change="handleSelectionChange"
      @view="handleView"
      @edit="handleEditRow"
      @delete="handleDeleteRow"
      @page-change="handlePageChange"
    />
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Edit, Delete as DeleteIcon, Refresh, Download } from '@element-plus/icons-vue'
import ActionButtons from '../components/ActionButtons.vue'
import SearchForm from '../components/SearchForm.vue'
import DataTable from '../components/DataTable.vue'
import { apiRequest } from '../../../utils/request'

export default {
  name: 'ListPage',
  components: {
    ActionButtons,
    SearchForm,
    DataTable
  },
  setup() {
    // 页面配置（tab 和标题）
    const pageConfig = reactive({
      title: '客户列表',
      tabs: [
        { key: 'all', label: '全部' },
        { key: 'vip', label: 'VIP客户' }
      ]
    })
    const activeTab = ref(pageConfig.tabs[0].key)
    const handleTabChange = (tab) => {
      activeTab.value = tab
      // 这里可以根据 tab 切换刷新数据
    }

    // 响应式数据
    const tableData = ref([])
    const total = ref(0)
    const selectedRows = ref([])
    const loading = ref(false)
    
    // 搜索参数
    const searchParams = ref({
      customerName: '',
      contactPerson: '',
      phone: '',
      status: '',
      dateRange: []
    })
    
    // 分页参数
    const pagination = reactive({
      page: 1,
      size: 20
    })
    
    // 模拟数据
    const mockData = [
      {
        id: 1,
        addDate: '2025-04-22',
        customerName: '张三公司',
        contactPerson: '张三',
        contactPhone: '13812345678',
        businessType: '业务员A',
        periodAmount: 10200.00,
        currentDebit: 5000.00,
        currentCredit: 3200.00,
        currentBalance: 1800.00,
        totalBalance: 12000.00,
        invoiceCount: 5,
        customerStatus: 1,
        customerLevel: 'VIP客户',
        contactAddress: '上海市浦东新区xxx路xxx号'
      },
      {
        id: 2,
        addDate: '2025-04-21',
        customerName: '李四企业',
        contactPerson: '李四',
        contactPhone: '13987654321',
        businessType: '业务员B',
        periodAmount: 8500.00,
        currentDebit: 0.00,
        currentCredit: 0.00,
        currentBalance: 0.00,
        totalBalance: 8500.00,
        invoiceCount: 3,
        customerStatus: 1,
        customerLevel: '普通客户',
        contactAddress: '北京市朝阳区xxx路xxx号'
      },
      {
        id: 3,
        addDate: '2025-04-20',
        customerName: '王五集团',
        contactPerson: '王五',
        contactPhone: '13611111111',
        businessType: '业务员C',
        periodAmount: 15600.00,
        currentDebit: 2000.00,
        currentCredit: 1500.00,
        currentBalance: 500.00,
        totalBalance: 16100.00,
        invoiceCount: 8,
        customerStatus: 0,
        customerLevel: '重要客户',
        contactAddress: '广州市天河区xxx路xxx号'
      }
    ]
    
    // 获取数据（真实接口）
    const fetchData = async () => {
      loading.value = true
      try {
        // 获取 openid、faid（实际项目应从登录信息或全局store获取）
        const openid = localStorage.getItem('openid') || ''
        const faid = 0 // 如有实际功能ID请替换
        // 构造请求参数
        const params = {
          key: searchParams.value.customerName,
          yewuy: searchParams.value.contactPerson,
          pagenumber: pagination.page,
          cxlx: activeTab.value === 'vip' ? 1 : 0,
          openid,
          faid
        }
        console.log('[客户列表] 请求参数:', params)
        const res = await apiRequest.getBusinessList(params)
        console.log('[客户列表] 接口响应:', res)
        // 兼容接口返回格式
        tableData.value = Array.isArray(res.data) ? res.data : (res.data?.list || [])
        total.value = res.data?.total || res.total || 0
      } catch (error) {
        ElMessage.error('获取数据失败')
      } finally {
        loading.value = false
      }
    }
    
    // 事件处理
    const handleSelectionChange = (selection) => {
      selectedRows.value = selection
    }
    
    const handleAdd = () => {
      ElMessage.success('新增功能')
      // 这里可以打开新增对话框或跳转到新增页面
    }
    
    const handleEdit = () => {
      if (selectedRows.value.length === 0) {
        ElMessage.warning('请选择要编辑的数据')
        return
      }
      if (selectedRows.value.length > 1) {
        ElMessage.warning('只能选择一条数据进行编辑')
        return
      }
      ElMessage.success('编辑功能')
      // 这里可以打开编辑对话框
    }
    
    const handleBatchDelete = async () => {
      if (selectedRows.value.length === 0) {
        ElMessage.warning('请选择要删除的数据')
        return
      }
      
      try {
        await ElMessageBox.confirm(
          `确定要删除选中的 ${selectedRows.value.length} 条数据吗？`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        ElMessage.success('删除成功')
        fetchData()
      } catch {
        ElMessage.info('已取消删除')
      }
    }
    
    const handleRefresh = () => {
      ElMessage.success('刷新成功')
      fetchData()
    }
    
    const handleExport = () => {
      ElMessage.success('导出功能')
      // 这里可以实现导出功能
    }
    
    const handleSearch = () => {
      pagination.page = 1
      fetchData()
    }
    
    const handleReset = () => {
      pagination.page = 1
      fetchData()
    }
    
    const handleView = (row) => {
      ElMessage.success(`查看客户：${row.customerName}`)
      // 这里可以打开详情对话框或跳转到详情页面
    }
    
    const handleEditRow = (row) => {
      ElMessage.success(`编辑客户：${row.customerName}`)
      // 这里可以打开编辑对话框
    }
    
    const handleDeleteRow = async (row) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除客户"${row.customerName}"吗？`,
          '提示',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        ElMessage.success('删除成功')
        fetchData()
      } catch {
        ElMessage.info('已取消删除')
      }
    }
    
    const handlePageChange = ({ page, size }) => {
      pagination.page = page
      pagination.size = size
      fetchData()
    }
    
    // 初始化
    onMounted(() => {
      fetchData()
    })
    
    // 动态按钮配置
    const actionButtons = [
      { type: 'add', label: '新增', btnType: 'primary' },
      { type: 'edit', label: '修改' },
      { type: 'view', label: '查看' },
      { type: 'all', label: '全部客户' },
      { type: 'unpaid', label: '未清客户' },
      { type: 'export', label: '导出' },
      { type: 'reset', label: '重置' }
    ]
    
    return {
      pageConfig,
      activeTab,
      handleTabChange,
      tableData,
      total,
      selectedRows,
      searchParams,
      pagination,
      handleSelectionChange,
      handleAdd,
      handleEdit,
      handleBatchDelete,
      handleRefresh,
      handleExport,
      handleSearch,
      handleReset,
      handleView,
      handleEditRow,
      handleDeleteRow,
      handlePageChange,
      actionButtons
    }
  }
}
</script>

<style scoped>
.list-page {
  padding: 20px;
  background: #f0f2f5;
  min-height: 100vh;
}
</style>